package com.edu.buservice.web.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.edu.buservice.biz.UserManger;
import com.edu.buservice.biz.model.Request.QueryUserRequest;
import com.edu.buservice.biz.model.Request.UpdateUserRequest;
import com.edu.buservice.biz.model.Request.UserRequest;
import com.edu.buservice.facade.constants.SessionKeyConstant;
import com.edu.buservice.util.model.R;
import com.edu.buservice.util.model.TenantUtil;
import com.edu.buservice.util.model.UserInfoDTO;
import com.edu.buservice.util.model.enums.ErrorCodeEnum;
import com.edu.buservice.util.model.error.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-03-09 14:59
 **/

@RestController
@RequestMapping("/buservice/user")
@Slf4j
public class UserController {

	@Autowired
	private UserManger userManger;


	/**
	 * 获取用户信息
	 */
	@GetMapping("/info")
	@SaCheckLogin
	@ResponseBody
	public R<UserInfoDTO> getUserInfo() {
		UserInfoDTO userInfoDTO = StpUtil.getSession().get(SessionKeyConstant.USER_INFO, new UserInfoDTO());
		if(Objects.isNull(userInfoDTO)){
			throw new BizException(ErrorCodeEnum.USER_NOT_FOUND);
		}
		return R.success(userInfoDTO);
	}


	/**
	 * 新添加用户
	 */
	@PostMapping("/addUser")
	@SaIgnore
	public R<?> addUser(@RequestBody @Validated UserRequest userRequest) {

		return userManger.addUser(userRequest);

	}

	/**
	 * 根据手机号查询改手机号的所有租户
	 */
	@GetMapping("/queryTenant/{phone}")
	@SaIgnore
	public R<?> queryTenant(@PathVariable("phone") String phone) {

		TenantUtil.clear();

		if(StrUtil.isBlank(phone) || phone.length() != 11){
			throw new BizException(ErrorCodeEnum.PARAM_ERROR, "手机号不能为空");
		}

		return userManger.queryByTenantLabel(phone);

	}

	/*
	* @author 范铁凝
	* @date 2025/4/14
	* 根据姓名模糊查询
	*/
	@PostMapping("/queryUserList")
	public R<?> queryUser(@RequestBody QueryUserRequest queryUserRequest){
		log.info("查询用户信息：{}",queryUserRequest);
		return userManger.queryUserByCondition(queryUserRequest);
	}

	/*
	* @author 范铁凝
	* @date 2025/4/17
	* 更新用户信息
	*/
	@PostMapping("/updateUser")
	public R<?> updateUser(@RequestBody UpdateUserRequest userRequest){
		log.info("更新用户信息：{}",userRequest);
		return userManger.updateUserInfo(userRequest);
	}



}
